import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import ChatView from '../views/ChatView.vue'
import Login from '../views/LoginView.vue'
import InterestingWebpage from '@/views/interestingWebpage/InterestingWebpage.vue'
import { checkLoginStatus } from '@/api/user'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/chat',
      name: 'chat',
      component: ChatView
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/interestingWebpage',
      name: 'interestingWebpage',
      component: InterestingWebpage
    }
  ]
})

// 全局路由守卫，在每次路由变化时检查登录状态
router.beforeEach(async (to, from, next) => {
  // 检查用户登录状态
  const response = await checkLoginStatus()
  const userStore = useUserStore()
  
  // 如果后端返回未登录，且本地有用户信息，则清除用户信息
  if (response.code === 200 && response.data === false && userStore.id) {
    userStore.clearUserInfo()
    // 可选：通知用户已退出登录
    // ElMessage.info('您的登录已过期，请重新登录')
  }
  // 继续导航
  next()
})

export default router
